
import re
import string

#sas variable name can not contain '/' and mus be les then 32 char long
sas_variable = lambda x_s: re.sub('_{1,}$','',upper_clean(string.strip(re.sub('/','_',x_s)[:30])))+'_'

upper_clean = lambda x_s: re.sub('\W','_',string.upper(string.strip(x_s)))

def glmap(file='gl.mapping'):
    """ """
    res = {}
    glmap = string.split(open('gl.mapping', 'r').read(),'\n')

    for r in glmap:
        if r <> '':
            r = re.sub('= SCAN\(in,\d{1,},\'\^\'\)', '', r)
            a,b =   string.strip(string.split(r, ';')[0]), \
                    string.strip(string.split(r, ';')[1])
            res[a] = b
    return res

class SasGLStrings:
    """ Create
    """
    def __init__(self, info):
        """ """
        self.info = info

    def atrb(self):
        """ """
        res = '\n'
        for k in sorted(self.info['@CSPAN'].keys()):
            cname = sas_variable(self.info['@CSPAN'][k]['HEADER'])

            # rename "ERROR" string to ER_ROR to avoid catchin those names as error
            cname = re.sub('ERROR', 'EROR', cname)

            # raise cspan + 1 for all columns
            ## why example : value 0 is not allowed in SAS FORMAT command
            ## why example : some loaded columns are prepended with apostrof because of Excel
            cspan = str(int(self.info['@CSPAN'][k]['SPAN'])+1)
            # FORMAT = $26.
            fmt_str = 'FORMAT = $'+ cspan
            res += '    %s%s%s.\n'%( cname, ' '*(40-len(cname)), fmt_str)
        res += '\n'
        return res

    def scan(self):
        """ """
        res = '\n'
        for k in sorted(self.info['@CSPAN'].keys()):
            cname = re.sub('_{2,}', '_', string.upper(self.info['@CSPAN'][k]['HEADER'])+'_')

            # rename "ERROR" string to ER_ROR to avoid catchin those names as error
            cname = re.sub('ERROR', 'EROR', cname)

            cspan = str(self.info['@CSPAN'][k]['HEADER'])
            # = SCAN(in,2,'^');
            scn_str = "= SCAN(in,%s,'%s');"%(int(k[1:])+1, self.info['@CDELR'])
            res += '    %s%s%s\n'%(cname, ' '*(40-len(cname)), scn_str)
        res += '\n'
        return res

    def drop(self):
        """ """
        res = '\n    drop    in\n'
        for k in sorted(self.info['@CSPAN'].keys()):
            item = re.sub('_{2,}', '_', string.upper(self.info['@CSPAN'][k]['HEADER'])+'_')

            # rename "ERROR" string to ER_ROR to avoid catchin those names as error
            item = re.sub('ERROR', 'EROR', item)

            res += '      %s%s\n'%(' '*(35-len(item)), item)
        res += '    ;\n'
        return res

    def list(self):
        """ """
        res = '\n'
        for k in sorted(self.info['@CSPAN'].keys()):
            item = re.sub('_{2,}', '_', string.upper(self.info['@CSPAN'][k]['HEADER'])+'_')

            # rename "ERROR" string to ER_ROR to avoid catchin those names as error
            item = re.sub('ERROR', 'EROR', item)

            res += '^%s'%(item)
        res += '\n'
        return res

    def ppAll(self):
        """ Pretty print all
        """
        print 'print self.atrb()'
        print self.atrb()
        print 'print self.scan()'
        print self.scan()
        print 'print self.drop()'
        print self.drop()
        print 'print self.list()'
        print self.list()

    def glMap(self, file='gl.mapping'):
        """ """
        glm = glmap(file)
        print glm        
